var app = getApp();
var url = app.url;
var pageNumber = 1;
var header = { 'content-type': 'application/x-www-form-urlencoded' }
Page({
  data: {
    showLoading: true, // 等待动画
    menu: '',
    chidx: 0,// 选中地区下标
    opType: '',// 1==开，0==关
    list: [],
    keyword: '',
    teamList: [],
    treamId: '',
    teamName: '',
    dataNum: 0,
    faultDescription: '',
    startTime: '',
    endTime: '',
    filterShow: false,
    // gzList: ['全部','路灯不亮', '灯杆损坏倾斜', '线缆外露损坏', '灯杆门缺损', '附近成片熄灯',],
    gzList: [
      {value:'全部',checked:false},
      {value:'单灯不亮',checked:false},
      {value:'线路故障',checked:false}, 
      {value:'控制箱故障',checked:false}, 
      {value:'灯杆门缺损',checked:false}, 
      {value:'灯杆缺陷',checked:false},
      {value:'乱挂广告牌',checked:false}, 
      {value:'紧急突发故障',checked:false}, 
      {value:'其他故障隐患',checked:false}, 
      {value:'日常巡检设备',checked:false}, 
    ],
    personList: [],
    personName: '',
    teamShow: false,
    userId: wx.getStorageSync('userId'),
    localUserId: wx.getStorageSync('userId'),
    gzShow: false,
    tabList: [
      { name: '待处理', value: 1 },
      { name: '已处理', value: 2 },
    ],
    tabIndex: 1,
    toDoNumber: 0,
    doneNumber: 0,
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    console.log(options)
    pageNumber = 1;
    if (options.keyword) this.setData({ keyword: options.keyword })
    this.getTeamList()
  },
  onShow: function () {
    // 页面显示
    pageNumber = 1;
    this.checkLogin()
    var name = wx.getStorageSync('userName')
    if (name) {
      this.getUserMeters(true)
    }


  },
  onReady: function () {
    // 页面渲染完成
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  onPullDownRefresh: function () {
    pageNumber = 1;
    this.getUserMeters(true)
  },
  onShareAppMessage: function () {

  },
  checkLogin: function () {
    var name = wx.getStorageSync('userName')
    if (name == '' || name == null) {
      wx.showModal({
        title: '提示',
        content: "用户未登录",
        confirmText: '去登录',
        showCancel: false,
        success: function () {
          wx.navigateTo({
            url: '../login/login',
          })
        }
      })
    }
  },
  getUserMeters: function (reload) {
    var that = this;
    var list = this.data.list;
    var params = {
      // serName: wx.getStorageSync('userName'), 
      pageSize: 20, pageNumber: pageNumber,
      deptId: wx.getStorageSync('deptId'),
      address: that.data.keyword,
      treamId: this.data.personName ? '' : that.data.treamId,
      faultDescription: that.data.faultDescription == '全部' ? '' : that.data.faultDescription,
      startTime: that.data.startTime,
      endTime: that.data.endTime,
      userName: this.data.personName,
      userId: this.data.userId,
    }
    console.log(params)
    var encodingStr = app.ecbEncrypto(params);
    console.log(encodingStr);
    wx.showLoading({
      title: '加载中',
    })


    this.getToDoList(encodingStr,reload)
    this.getDoneList(encodingStr,reload)
  },
  getToDoList(encodingStr,reload) {
    var that = this;
    var list = this.data.list;
    wx.request({
      url: url + '/api/account/getSysExceptionReportList.htm',
      data: encodingStr,
      method: 'POST',
      header: header,
      success: (res) => {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr);
        if(this.data.tabIndex == 1){
          rest.result.content.forEach(function (item) {
            item.createTime = js_date_time(item.createTime);
            if (item.dealTime) {
              item.dealTime = js_date_time(item.dealTime);
            }
          })
          if (rest.isSuccess == 0) {
            if (!reload) {
              list = list.concat(rest.result.content);
            } else {
              list = rest.result.content
            }
            that.setData({ list: list, dataNum: rest.result.totalElements })
          } else {
            wx.showModal({
              title: '提示',
              content: rest.errorMsg,
              showCancel: false
            })
          }
        }
        that.setData({toDoNumber: rest.result.totalElements })
        console.log(rest)
      },
      complete: function () {
        wx.stopPullDownRefresh()
        that.setData({ showLoading: false })
        wx.hideLoading();
      }
    })
  },
  getDoneList(encodingStr,reload) {
    var that = this;
    var list = this.data.list;
    wx.request({
      url: url + '/web/exceptionReport/getFinshList.htm',
      data: encodingStr,
      method: 'POST',
      header: header,
      success: (res) => {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr);
        if(this.data.tabIndex == 2){
          rest.result.content.forEach(function (item) {
            item.createTime = js_date_time(item.createTime);
            if (item.dealTime) {
              item.dealTime = js_date_time(item.dealTime);
            }
          })
          if (rest.isSuccess == 0) {
            if (!reload) {
              list = list.concat(rest.result.content);
            } else {
              list = rest.result.content
            }
            that.setData({ list: list, dataNum: rest.result.totalElements })
          } else {
            wx.showModal({
              title: '提示',
              content: rest.errorMsg,
              showCancel: false
            })
          }
        }
        that.setData({ doneNumber: rest.result.totalElements })
        console.log(rest)
      },
      complete: function () {
        wx.stopPullDownRefresh()
        that.setData({ showLoading: false })
        wx.hideLoading();
      }
    })
  },
  // 跳转
  showSzByName: function (e) {
    var idx = e.currentTarget.dataset.idx
    var list = this.data.fzList
    wx.setStorageSync("area" + idx, list[idx])// 缓存数据
    wx.navigateTo({
      url: '../control/zdarea?idx=' + idx,
    })
  },
  callPhone: function (e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone,
      success: function () {

      },
      fail: function () {

      }
    });
  },
  bindToDetail: function (e) {
    var id = e.currentTarget.dataset.id;
    var dealwithRemark = e.currentTarget.dataset.dealwithremark || '';
    var userName = e.currentTarget.dataset.username || '';
    const url = this.data.tabIndex == 1 ? '../reportList/reportDetail?id=' + id
      : '../reportList/processedDetail?id=' + id + '&dealwithRemark=' + dealwithRemark + '&userName=' + userName
    wx.navigateTo({
      url,
    })
  },
  tolower: function () {
    pageNumber++;
    this.getUserMeters();
  },
  toSearch() {
    console.log(this.data.keyword)
    pageNumber = 1;
    this.getUserMeters(true)
    this.setData({
      filterShow: false,
      teamShow: false,
      gzShow: false
    })
  },
  clearSearch() {
    this.setData({
      // keyword: '',
      // treamId: '',
      // faultDescription:'',
      startTime: '',
      endTime: '',
      // teamName:'',
    })
  },
  inputgetKeyword(e) {
    this.setData({
      keyword: e.detail.value
    })
  },
  getTeamList() {
    var that = this;
    var params = {
      pageNumber: 1,
      pageSize: 10000,
      deptid: wx.getStorageSync('deptId'),
      type: 1,
    }
    var paramsCode = app.ecbEncrypto(params)
    wx.request({
      url: app.url + '/web/sysTream/getList.htm',
      data: paramsCode,
      method: 'POST',
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data);
        var rest = JSON.parse(decodingStr)
        console.log(rest)
        if (rest.isSuccess == 0) {
          var list = rest.result.content
          that.setData({
            teamList: list,
          })
        }
      },
      complete: function () {

      }
    })
  },
  teamChange(event) {
    const index = event.detail.value;
    const obj = this.data.teamList[index];
    this.setData({ treamId: obj.id, teamName: obj.name })
    this.toSearch()
  },
  startTimeChange(event) {
    this.setData({ startTime: event.detail.value })
  },
  endTimeChange(event) {
    this.setData({ endTime: event.detail.value })
  },
  showFilter() {
    this.setData({ filterShow: true })
  },
  inputChange(e) {
    let obj = {};
    obj[e.currentTarget.dataset.key] = e.detail.value
    this.setData(obj)
  },
  desChange(event) {
    const index = event.detail.value;
    const value = this.data.gzList[index];
    this.setData({ faultDescription: value == '全部' ? '' : value })
    this.toSearch()
  },
  checkboxChange: function (e) {
    var cboxs = e.detail.value;
    var val = cboxs.toString();
    let teamList = this.data.teamList
    teamList.forEach((item, index) => {
      item.checked = cboxs.includes(item.id.toString())
    })
    this.setData({ treamId: val, teamList, personName: '' })
    if (cboxs) {
      this.getPersonList()
    } else {
      this.setData({ personList: [] })
    }
  },
  clearTeam() {
    let teamList = this.data.teamList
    teamList.forEach((item, index) => {
      item.checked = false
    })
    this.setData({ treamId: '', personName: '', personList: [], teamList })
  },
  getPersonList() {
    var that = this;
    var list = this.data.list;
    var header = { 'content-type': 'application/x-www-form-urlencoded' }
    var params = {
      pageSize: 1000,
      pageNumber: 1,
      treamId: that.data.treamId,
    }
    console.log(params);
    var encodingStr = app.ecbEncrypto(params);
    console.log(encodingStr);
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: url + '/web/baseAccount/getList2.htm',
      data: encodingStr,
      method: 'POST',
      header: header,
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        console.log(decodingStr)
        var rest = JSON.parse(decodingStr);
        console.log(rest)
        if (rest.isSuccess == 0) {
          that.setData({ personList: rest.result.content, })
        } else {
          wx.showModal({
            title: '提示',
            content: rest.errorMsg,
            showCancel: false
          })
        }
        console.log(rest)
      },
      complete: function () {
        wx.stopPullDownRefresh()
        that.setData({ showLoading: false })
        wx.hideLoading();
      }
    })
  },
  personChange(e) {
    const cboxs = e.detail.value
    let personList = this.data.personList
    personList.forEach((item, index) => {
      item.checked = cboxs == item.loginName
    })
    this.setData({ personName: cboxs, personList })
  },
  showTeam() {
    this.setData({ teamShow: true })
  },
  showGz() {
    this.setData({ gzShow: true })
  },
  clearGz() {
    let gzList = this.data.gzList
    gzList.forEach((item, index) => {
      item.checked = false
    })
    this.setData({
      faultDescription: '',
      gzList
    })
  },
  checkboxChangeCom(e) {
    const { listname, listkey } = e.currentTarget.dataset;
    var cboxs = e.detail.value;
    var faultItems = this.data[listname];
    console.log(cboxs)
    console.log(faultItems)
    faultItems.forEach((item, index) => {
      item.checked = cboxs == item.value
    })
    const obj = {};
    obj[listname] = faultItems;
    obj[listkey] = cboxs.toString();
    console.log(obj);
    this.setData(obj);
    console.log(e)
  },
  filterMine() {
    this.clearTeam()
    this.setData({
      userId: this.data.userId ? '' : wx.getStorageSync('userId')
    })
    this.toSearch()
  },
  changeTab(e) {
    const value = e.currentTarget.dataset.value;
    this.setData({
      tabIndex: value,
    })
    pageNumber = 1;
    this.getUserMeters(true)
  }
});


function js_date_time(unixtime) {
  var dateTime = new Date(parseInt(unixtime))
  var year = dateTime.getFullYear();
  var month = (dateTime.getMonth() + 1) < 10 ? "0" + (dateTime.getMonth() + 1) : (dateTime.getMonth() + 1);
  var day = dateTime.getDate() < 10 ? "0" + dateTime.getDate() : dateTime.getDate();
  var hour = dateTime.getHours() < 10 ? "0" + dateTime.getHours() : dateTime.getHours();
  var minute = dateTime.getMinutes() < 10 ? "0" + dateTime.getMinutes() : dateTime.getMinutes();
  var second = dateTime.getSeconds();
  var now = new Date();
  var now_new = Date.parse(now.toDateString());  //typescript转换写法
  var milliseconds = now_new - dateTime;
  var timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
  return timeSpanStr;
}